<?php
class Cabin extends Page {

	static $db = array(
		'Recipient' => 'Varchar(255)',
		'ConfirmationText' => 'HTMLText',
	);
	
	static $has_many = array(
		'Bookings' => 'CabinBooking',
		'BookedDates' => 'CabinBookedDates'
	);
	
	
	function getCMSFields() {
		$fields = parent::getCMSFields();
		
		$fields->addFieldToTab('Root.Content.Einstellungen', new TextField('Recipient','Reservationsempfänger'));
		$fields->addFieldToTab('Root.Content.Einstellungen', new HtmlEditorField('ConfirmationText','Bestätigungstext'));
				
		$reservationTable = new DataObjectManager(
			$this,
         	'Bookings',
         	'CabinBooking',
			array('Name' => 'Name','DateFrom' => 'von','DateTo' => 'bis'),
			'getCMSFields_forPopup',
			"CabinID = {$this->ID} AND (DateTo >= CURDATE() OR DateFrom >= CURDATE())",
			'DateFrom ASC'
      		);
		$reservationTable->popupClass = 'CabineBookingObjectManager_Popup'; 
		$fields->addFieldToTab('Root.Content.Reservationen',$reservationTable);

		$bookedOutTable = new DataObjectManager(
			$this,
         	'BookedDates',
         	'CabinBookedDates',
			array('DateFrom' => 'von','DateTo' => 'bis'),
			'getCMSFields_forPopup',
			"CabinID = {$this->ID} AND (DateTo >= CURDATE() OR DateFrom >= CURDATE())",
			'DateFrom ASC'
      		);
		//$availableTable->popupClass = 'CabineBookingObjectManager_Popup'; 
		$fields->addFieldToTab('Root.Content.Verfügbarkeit',$bookedOutTable);
		
		return $fields;
	}
	
	public function checkIfAvailable($dateFrom, $dateTo) {

		$bookings = DataObject::get('CabinBookedDates',
			'CabinID = ' .$this->ID . " AND ( 
			'".$dateFrom."' BETWEEN `CabinBookedDates`.dateFrom AND DATE_SUB(`CabinBookedDates`.dateTo,INTERVAL 1 DAY)
			OR
			'".$dateTo."' BETWEEN DATE_ADD(`CabinBookedDates`.dateFrom,INTERVAL 1 DAY) AND `CabinBookedDates`.dateTo
			OR 
			('".$dateFrom."' < `CabinBookedDates`.dateFrom AND ".$dateTo." > `CabinBookedDates`.dateTo)
			)");
		
		

		if ($bookings) {
			return false;
		}
		return true;	
	}
	
}
 
class Cabin_Controller extends Page_Controller {
	function init(){
		parent::init();
	}
	

	
	function BookingForm() {
		$fieldset = CabinBooking::getFormFields();
		$fieldset->push(new HiddenField('CabinID','CabinID',$this->ID));
		$actions = new FieldSet(
			new FormAction('doBooking', 'Absenden')
		);
		
		$validation = new CabinBookingFields(array('NumberOfPersons','Name','FirstName','Street','Zip','City','Country','TelNumber','email'));

		return new Form($this, 'BookingForm', $fieldset, $actions, $validation);
	}
	
	
	/**
	 * @param array $data
	 * @param Form $form
	 * @return void
	 */
	function doBooking($data,$form) {

		if ($form->validate()) {
			$booking = new CabinBooking();
			$form->saveInto($booking);
			$booking->CabinID = $this->ID;
			$booking->write();
			
			$email = new Email();
			$email->setTemplate('BookMail');
			$email->setTo($this->Recipient);
	        $email->setFrom( $booking->Email );
	        $email->setSubject( 'Neue Reservation' );
	        $data['Title'] = $this->Title;
	        $email->populateTemplate($data);
			$email->send();
			Director::redirect($this->URLSegment . '/confirmation');
		} else {
			Session::set("FormInfo.Form_BookingForm.data", $data);
			return Director::redirectBack();
		}
	}
	
	public function BookingOverview() {
		Requirements::css("fieldExtension/css/ui.datepicker.css");
		Requirements::css("cabinBooker/css/style.css");
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/plugins/livequery/jquery.livequery.js');
	    Requirements::javascript("fieldExtension/javascript/jquery-ui-1.7.2.min.js");
	    Requirements::javascript("fieldExtension/javascript/ui.datepicker.js");
	    
	    $bookedDates = DataObject::get('CabinBookedDates',
			"CabinID = {$this->ID} AND (DateTo >= '".date('Y-m-01')."' OR DateFrom >= ".date('Y-m-01').")",'DateFrom');
		
	    $jsDateScript = "var bookedDates = new Array(\n";
		if ($bookedDates) {
		    
			foreach ($bookedDates AS $bookedDate) {
				$jsDateScript .= "new Array(new Date('".date('r',strtotime($bookedDate->DateFrom))."'),";
				$jsDateScript .= ($bookedDate->DateTo)?"new Date('".date('r',strtotime($bookedDate->DateTo))."')":"null";
				$jsDateScript .= "),";
		    	//$jsArray[] = array(date('Y,m,d',strtotime($bookedDate->DateFrom)),date('Y,m,d',strtotime($bookedDate->DateTo)));
		    }
		    $jsDateScript = substr($jsDateScript,0,strlen($jsDateScript)-1);   
		}
		$jsDateScript .= "\n);\n";
	    
	    $datePickerController = new CalendarPickerField_Controller();
	    $calLang = $datePickerController->CalendarLang();
	    $calLang = substr($calLang,1,strlen($calLang)-2);

	    Requirements::customScript($jsDateScript);
	    Requirements::customScript('
	    
jQuery(document).ready(function(){
	jQuery("#OverviewCalendar").datepicker(
			{
				minDate: new Date('.date('Y,').(intval(date('m'))-1).date(',d').'),
				beforeShowDay: function(date) {
					dayConfig = new Array();
					dayConfig.push(false);
					var cssClass= "opFix free";
					var dateTo = false;
					for(var i=0; i < bookedDates.length; i++ ) {
						if (dateTo && bookedDates[i][0].getTime() == date.getTime()) {
							cssClass = "booked";
							dateTo = false;
						} else {					
							if (bookedDates[i][0].getTime() == date.getTime()) {
								cssClass = "opFix bookedEvening";
							} else if (bookedDates[i][1].getTime() == date.getTime()) {
								cssClass = "opFix bookedMorning";
								dateTo = true;
								
							} else if (bookedDates[i][0].getTime() < date.getTime() && bookedDates[i][1].getTime() > date.getTime()) {
								cssClass = "opFix booked";
							}
						}
					}
					dayConfig.push(cssClass);
					
					return dayConfig;
					
				},'.$calLang.'
			
			}
			
			
	);
});	
	    
	    ');
	    
		return '
				<table class="legendTable">
					<tr>
						<td class="freelegend legend"></td>
						<td class="legend"></td>
						<td>freie Plätze</td>
					</tr>
					<tr>
						<td class="bookedlegend legend"></td>
						<td></td>
						<td>ausgebucht</td>
					</tr>
					<tr>
						<td class="bookedEveninglegend legend"></td>
						<td class="bookedMorninglegend legend"></td>
						<td>Nacht ausgebucht</td>
					</tr>

				</table>
		';
	}

	
}

?>